#include "graphicsfactory.h"

CGraphicsFactory::CGraphicsFactory()
{
	
	InitFreeTypeLibrary();
	
	m_pMaterialLine = new CFactoryLine_Map;
	m_pRawMaterialLine = new CFactoryLine_Map;
	
}

CGraphicsFactory::~CGraphicsFactory()
{
	
	CleanFreeTypeLibrary();
	
	delete m_pMaterialLine;
	delete m_pRawMaterialLine;
	
}

CFontMaterial * CGraphicsFactory::LoadFont( std::string name, std::string filename, int size )
{

	CFontMaterial * font = NULL;
	
	if( ( font = ( CFontMaterial * )m_pMaterialLine->Find( name ) ) )
		return font;
	
	font = new CFontMaterial;
	
	font->SetHeight( size );
	font->LoadFromFile( filename );
	font->SetTag( name );
	
	m_pMaterialLine->Add( name, font );
	
}

CMaterial * CGraphicsFactory::LoadMaterial( std::string filename )
{
	
	CMaterial * mat = NULL;
	
	if( ( mat = ( CMaterial * )m_pMaterialLine->Find( filename ) ) )
		return mat;
	
	std::vector< CMaterialFrame * > matFrames;
	
	bool endanim = true;
	int repeatframe = -1;
	
	if( filename.find( ".spr" ) != std::string::npos )
	{
		
		std::ifstream file( filename.c_str() );
		
		std::string framedir;
		int pause;
		double ox, oy;
		
		while( !file.eof() )
		{
			
			file >> framedir;
			
			if( framedir == "END" )
				break;
			else if( framedir == "REPEAT" )
			{
				
				file >> repeatframe;
				endanim = false;
				break;
				
				
			} else
			{
				
				file >> pause >> ox >> oy;
				
			}
			
			CMaterialFrame * matFrame = new CMaterialFrame;
	
			if( ( CopyMaterialFrame( framedir, matFrame ) ) == NULL )
			{	
			
				CMaterialFrame * newframe = LoadMaterialFrame( framedir );
				newframe->CopyOver( matFrame );
				
			}
	
			matFrame->SetPause( pause );
			
			matFrame->SetTag( framedir );
			
			matFrame->SetFrameOffset( ox, oy );
	
			matFrames.push_back( matFrame );
			
			
		}
		
		file.close();
		
	} else
	{
		
		CMaterialFrame * matFrame = new CMaterialFrame;
	
		if( ( CopyMaterialFrame( filename, matFrame ) ) == NULL )
		{	
			
			CMaterialFrame * newframe = LoadMaterialFrame( filename );
			newframe->CopyOver( matFrame );
			
		}
	
			
		matFrames.push_back( matFrame );
		
	}
	
	mat = new CMaterial;

	for( int j = 0; j < matFrames.size(); j++ )
		mat->AddFrame( matFrames[j] );
	
	mat->SetTag( filename );
	mat->SetRepeatFrame( repeatframe );
	
	m_pMaterialLine->Add( filename, mat );
	
	return mat;

	/*
	CMaterial * m = new CMaterial;

	m->LoadFromFile( file );
	
	int c = m->GetFrameCount();

	for( int j = 0; j < c; j++ )
	{

		std::string texdir = m->GetFrameTag( j );
		CMaterialFrame * f = NULL;
	
		if( ( f = GetMaterialFrame( texdir ) ) == NULL )
			f = LoadMaterialFrame( texdir );	

		m->SetFrameSize( j, f->GetWidth(), f->GetHeight() );
		m->SetFrameTexturePtr( j, &f->GetTexture() );
		
		
	}

	if( c > 0 )
	{

		m_pMaterialLine->Add( m->GetFrameTag( 0 ), m );
	
	}
	
	
	return m;
	*/
	
}